import Taro, { getCurrentInstance } from "@tarojs/taro";
import React, { useState, useEffect } from "react";
import { View, Input, Button, ScrollView } from "@tarojs/components";
import def from "../../../assets/default.jpg";
import { getUserInfo, sendMessage, getMessage, readMessage } from "./api";
import css from "./index.module.less";

export default function Index() {
  const { otherId, otherUuid } = getCurrentInstance().router.params;
  const initialState = {
    "avatar": "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132",
    "concernedNumber": 0,
    "created": "",
    "email": "",
    "fansNumber": 0,
    "id": 0,
    "status": 0,
    "tel": "",
    "title": null,
    "username": "微信用户",
    "uuid": ""
  }
  const [otherUser, setOtherUser] = useState(initialState);
  const [myUser, setMyUser] = useState(initialState);
  const [messages, setMessages] = useState([])
  const [inputValue, setInputValue] = useState('')

  useEffect(() => {
    getUserInfo(otherId).then((res) => {
      if (res.code === 200) {
        const userInfo = res.data;
        setOtherUser(userInfo);
      }
    })
    Taro.getStorage({
      key: 'userInfo',
      success: function (res) {
        const userInfo = res.data;
        setMyUser(userInfo);
        const data = {
          myUuid: userInfo.uuid,
          otherUuid: otherUuid
        }
        getMessage(data).then((res) => {
          if (res.code === 200) {
            const info = res.data;
            const newMessage = [];
            for (let i = 0; i < info.length; i++) {
              const element = info[i];
              if (element.myUuid === userInfo.uuid) {
                newMessage.push({state: 1, value: element.message})
              } else {
                newMessage.push({state: 0, value: element.message})
              }
            }
            setMessages(newMessage);
            console.log(newMessage);
          }
        })
        readMessage(data);
      }
    })
  }, [])


  const handleInput = (e) => {
    setInputValue(e.target.value)
  }

  const myHandleSend = () => {
    if (inputValue) {
      setMessages([...messages, {state: 1, value: inputValue}])
      setInputValue('')
      const data = {
        myUuid: myUser.uuid,
        otherUuid: otherUser.uuid,
        message: inputValue
      }
      sendMessage(data).then((res) => {
        if (res.code === 200) {
          console.log(res.data);
        }
      })
    }
  }

  const scrollStyle = {
      height: '30rem'
  }

  const [isLoad, setIsLoad] = useState(false);
  const onLoad = () => {
    setIsLoad(true);
  }

  const onError = () => {
    setIsLoad(false);
  }
  return (
    <React.Fragment>
      <View className={css.app}>
        <ScrollView className={css.chat}
          scrollY
          scrollWithAnimation
          scrollTop={0}
          style={scrollStyle}
          lowerThreshold={10}
          upperThreshold={10}
          >
          {messages.map((message, index) => (
            <View key={index} className={message.state === 1? css.right : css.left}>
              <View>{message.value}</View>
              <image className={css.img} src={isLoad ? (message.state === 1? myUser.avatar : otherUser.avatar) : def} onLoad={onLoad} onError={onError}/>
            </View>
          ))}
        </ScrollView>
        <View className={css.box}>
          <Input className={css.message} value={inputValue} onInput={handleInput} placeholder="请输入消息"/>
          <Button className={css.send} onClick={myHandleSend}>发送</Button>
        </View>
      </View>
    </React.Fragment>
  );
}
